    package com.headwind.logistics.order.service.impl;

    import com.headwind.logistics.common.pojo.Employee;
    import com.headwind.logistics.common.pojo.ExpressGrant;
    import com.headwind.logistics.common.pojo.GoodsIssueType;
    import com.headwind.logistics.common.pojo.PutSendInfo;
    import com.headwind.logistics.order.dto.OrderDto;
    import com.headwind.logistics.order.entity.Order;
    import com.headwind.logistics.order.entity.OrderCargo;
    import com.headwind.logistics.order.entity.OrderServiceFee;
    import com.headwind.logistics.order.entity.OrderTail;
    import com.headwind.logistics.order.mapper.OrderMapper;
    import com.headwind.logistics.order.mapper.PlanOrderMappder;
    import com.headwind.logistics.order.service.inter.OrderServiceInter;
    import com.headwind.logistics.order.util.OrderUtil;
    import org.json.JSONObject;
    import org.json.JSONException;
    import org.springframework.stereotype.Service;
    import org.springframework.transaction.annotation.Transactional;

    import javax.annotation.Resource;
    import javax.servlet.http.HttpSession;
    import java.text.SimpleDateFormat;
    import java.util.ArrayList;
    import java.util.Date;
    import java.util.List;

    /**
    * @Author 盛夏
    * @Date 2020-07-20 下午 8:18
    * @Version 1.0
    * @DESCRIPTION 填写类作用描述
    */
    @Service
    public class OrderServiceImpl implements OrderServiceInter {

    @Resource
    private OrderMapper orderMapper;

    @Resource
    private PlanOrderMappder planOrderMappder;

    @Transactional
    @Override
    public int addOrder(int beginBranch, int endBranch,String courierOdd, HttpSession session,String planOrder,
                        String cargoJson, String costJson) throws JSONException{
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
        String orderOdd = "NFD"+ OrderUtil.getUUID();

        JSONObject json = new JSONObject(planOrder);

        //获取订单号
        String recordedNumber = json.getString("recordedNumber");

        Order order = new Order();
        order.setOrderOdd(orderOdd);
        order.setMakeCargoMethod((planOrderMappder.queryPlanOrderByOdd(recordedNumber)).getMakeCargoMethod());
        order.setCourierOdd(courierOdd);
        order.setOrderDate(df.format(new Date()));
        order.setUserId((planOrderMappder.queryPlanOrderByOdd(recordedNumber)).getCustomerId());
        order.setOrderWaybillId(0L);
        order.setGetSiteId((long)beginBranch);
        order.setSetSitId((long)endBranch);

        order.setEmployeeId(((Employee)session.getAttribute("EMPLOYEE")).getEmployeeId());

        //新增订单
        int count = orderMapper.addOrder(order);


            //新增订单事件
            OrderTail orderTail = new OrderTail();
            orderTail.setOrderTailTime(df.format(new Date()));
            orderTail.setOrderTailIncident("您的订单已被受理,正在等待装车  操作人:"+
                    ((Employee)session.getAttribute("EMPLOYEE")).getEmployeeName());
            orderTail.setOrderId(order.getId());
            orderMapper.addOrderTail(orderTail);

            //截取得到json格式货物数据
            cargoJson = cargoJson.substring(1, cargoJson.length() - 1);

            //分隔数据
            String[] cargoJsons = cargoJson.split("},");
            //循环货物数据

            for (int i = 0; i < cargoJsons.length; i++) {
                String cargo = null;
                String backType = "0";
                String number = "0";
                String weight = "0";
                String volume = "0";
                String value = "0";

                //当循环到最后时不需要拼接  }
                if (i == cargoJsons.length - 1) {
                    JSONObject jsonObject = new JSONObject(cargoJsons[i]);
                    cargo = jsonObject.getString("cargo");
                    backType = jsonObject.getString("backType");
                    number = jsonObject.getString("backType");
                    weight = jsonObject.getString("weight");
                    volume = jsonObject.getString("volume");
                    value = jsonObject.getString("value");
                } else {
                    JSONObject jsonObject = new JSONObject(cargoJsons[i] + "}");
                    cargo = jsonObject.getString("cargo");
                    backType = jsonObject.getString("backType");
                    number = jsonObject.getString("number");
                    weight = jsonObject.getString("weight");
                    volume = jsonObject.getString("volume");
                    value = jsonObject.getString("value");
                }

                if (!cargo.equals("") || !backType.equals("0")) {
                    OrderCargo orderCargo = new OrderCargo();
                    orderCargo.setOrderCargoName(cargo);
                    orderCargo.setOrderCargoNumber(Integer.parseInt(number));
                    orderCargo.setOrderPackID(Long.parseLong(backType));
                    orderCargo.setOrderCargoWeight(weight);
                    orderCargo.setOrderCargoVolume(volume);
                    orderCargo.setOrderID(order.getId());
                    orderCargo.setOrderCargoMoney(value);
                    orderMapper.addOrderCargo(orderCargo);
                }

            }

            //截取得到json格式费用数据

            if (costJson.length() >= 2 && costJson != null) {

                costJson = costJson.substring(1, costJson.length() - 1);

                //分隔数据
                String[] costJsons = costJson.split("},");

                for (int i = 0; i < costJsons.length; i++) {
                    String feeNmae = null;
                    String taxRate = null;
                    String amountReceivable = null;
                    String taxes = null;
                    String income = null;

                    if (i == costJsons.length - 1) {
                        JSONObject jsonObject = new JSONObject(costJsons[i]);
                        feeNmae = jsonObject.optString("feeName");
                        taxRate = jsonObject.optString("taxRate");
                        amountReceivable = jsonObject.optString("amountReceivable");
                        taxes = jsonObject.optString("taxes");
                        income = jsonObject.optString("income");
                    } else {
                        JSONObject jsonObject = new JSONObject(costJsons[i] + "}");

                        feeNmae = jsonObject.optString("feeName");
                        taxRate = jsonObject.optString("taxRate");
                        amountReceivable = jsonObject.optString("amountReceivable");
                        taxes = jsonObject.optString("taxes");
                        income = jsonObject.optString("income");
                    }
                    OrderServiceFee serviceFee = new OrderServiceFee();
                    serviceFee.setFeeTypeId(Long.parseLong(feeNmae));
                    serviceFee.setAmountReceivable(amountReceivable);
                    serviceFee.setTaxRate(taxRate);
                    serviceFee.setTaxes(taxes);
                    serviceFee.setIncome(income);
                    serviceFee.setOrderId(order.getId());

                    orderMapper.addOrderService(serviceFee);
                }
            }

            List<ExpressGrant> expressGrants = planOrderMappder.queryExpressGrant(Integer.toString(beginBranch));

            out: for (ExpressGrant expressGrant:expressGrants){
                //起始单号
                Long expressGrantStartNum = Long.parseLong(expressGrant.getExpressGrantStartNum());
                //已使用数量
                int yUse = expressGrant.getYUse();
                //如果使用数量小余发放数量
                if (yUse < expressGrant.getGrantCount()) {
                    orderMapper.updateExpressGrantByID(expressGrant.getExpressGrantId());
                    break out;
                }
            }

            //修改预录单状态为已接获
            count = planOrderMappder.updatePlanOrderStart("1",recordedNumber);

            //地址表对象
            PutSendInfo putSendInfo = new PutSendInfo();
            putSendInfo.setPutSendId(planOrderMappder.queryPlanOrderByOdd(recordedNumber).getSendId());
            putSendInfo.setOrderId(order.getId());
            //修改地址表数据
            planOrderMappder.updatePutSendInfo(putSendInfo);

            putSendInfo.setPutSendId(planOrderMappder.queryPlanOrderByOdd(recordedNumber).getPutId());
            planOrderMappder.updatePutSendInfo(putSendInfo);

        return count;
    }

    @Override
    public List<GoodsIssueType> queryGoodsIssueType() {
        return orderMapper.queryGoodsIssueType();
    }

    @Override
    public List<OrderDto> queryOrderByExpressGrantOdd(String expressGrantStartNum, String expressGrantEndNum) {
        return orderMapper.queryOrderByExpressGrantOdd(expressGrantStartNum,expressGrantEndNum);
    }

    @Override
    public List<OrderDto> queryOrderByPage(Integer page,Integer limit,Long empId) {
        List<OrderDto> list = new ArrayList<>();

        List<OrderDto> orderDtos = orderMapper.queryOrderByPage((page-1)*limit,limit,empId);

        for (OrderDto orderDto1 : orderDtos) {
            System.out.println("交付方式"+orderDto1.getMakeCargoMethod());

            OrderDto orderDto = new OrderDto();
            int number = 0;
            int volume = 0;
            double totalMoney = 0;
            int weight = 0;

            List<OrderCargo> orderCargos = orderDto1.getOrderCargos();

            for (OrderCargo orderCargo : orderCargos) {
                number += orderCargo.getOrderCargoNumber();
                volume += Integer.parseInt(orderCargo.getOrderCargoVolume());
                totalMoney += Double.parseDouble(orderCargo.getOrderCargoMoney());
                weight += Integer.parseInt(orderCargo.getOrderCargoWeight());
            }

            int carriageStart = 0;
            List<OrderDto> list1 = orderMapper.querySeriveFeeByOrderOdd(orderDto1.getOrderOdd());
            String feeName = null;
            for (OrderDto dto:list1){
                if (dto.getFeeName().equals("加急费")){
                    feeName = "加急";
                }else {
                    feeName = "普通";
                }

            }


            orderDto.setOrderOdd(orderDto1.getOrderOdd());      //订单号
            orderDto.setCourierOdd(orderDto1.getCourierOdd());  //面单号
            orderDto.setOrderDate(orderDto1.getOrderDate());    //下单时间
            orderDto.setOrderStatus(orderDto1.getOrderStatus());//订单状态
            orderDto.setMakeCargoMethod(orderDto1.getMakeCargoMethod());
            orderDto.setUserName(orderDto1.getUserName());      //客户姓名
            orderDto.setUserPhone(orderDto1.getUserPhone());    //客户电话
            orderDto.setSendAddress(orderDto1.getSendAddress());    //出发网点
            orderDto.setGoalAddress(orderDto1.getGoalAddress());    //目的网点
            orderDto.setSendOutDate(orderDto1.getSendOutDate());    //实际发运日期
            orderDto.setArriveDate(orderDto1.getArriveDate());      //实际运抵日期
            orderDto.setUpdateTime(orderDto1.getUpdateTime());      //修改时间
            orderDto.setEmployeeName(orderDto1.getEmployeeName());  //员工姓名
            //orderDto.setCarriageStart(orderDto1.getCarriageStart());   //运输性质
            orderDto.setFeeName(feeName);
            orderDto.setReceiptStart(orderDto1.getReceiptStart());      //回单状态

            orderDto.setCargoNmae((orderCargos.get(0)).getOrderCargoName());
            orderDto.setNumber(Integer.toString(number));

            orderDto.setVolume(Integer.toString(volume));
            orderDto.setTotalMoney(totalMoney);
            orderDto.setWeight(Integer.toString(weight));

            list.add(orderDto);
        }


        return list;
    }

    @Override
    public int queryOrderCount() {
        return orderMapper.queryOrderCount();
    }

    @Override
    public List<OrderDto> queryServiceFeeByOrderOdd(String orderOdd) {
        return orderMapper.querySeriveFeeByOrderOdd(orderOdd);
    }

    @Override
    public List<OrderTail> queryOrderTailByOrderId(String orderOdd) {
        return orderMapper.queryOrderTailByOrderId(orderOdd);
    }

    @Override
    public int loginDeleteOrder(String orderOdd, HttpSession session) {
        Long employeeId = ((Employee) session.getAttribute("EMPLOYEE")).getEmployeeId();
        int count = 0;
        if (employeeId == 1){
            count = orderMapper.deleteOrder(orderOdd);
        }else {
            count = orderMapper.updateOrderDele(orderOdd);
        }
        return count;
    }
    }
